<script setup>
import { adminAddService, adminChangeStateService, adminDeleteService, adminEditService, adminListWithConditionService } from '@/api/admin'
import {
    Edit,
    Delete
} from '@element-plus/icons-vue'
import { ref } from 'vue'
import { Plus } from '@element-plus/icons-vue'
//导入token
import { userTokenStore } from '@/store/token'
const tokenStore = userTokenStore();
import '@vueup/vue-quill/dist/vue-quill.snow.css'
import { ElMessage, ElMessageBox } from 'element-plus'

//状态数据模型
const sexOptions = ref([
    { label: '男', value: '1' },
    { label: '女', value: '0' }
]);
const statusOptions = ref([
    { label: '启用', value: '1' },
    { label: '禁用', value: '0' }
]);
const sexHashmap = new Map([['1', '男'], ['0', '女']]);
const statusHashmap = new Map([[1, '启用'], [0, '禁用']]);


//商品数据模型
const admins = ref([
    {
        "id": "1",
        "username": "admin",
        "name": "管理员",
        "sex": "男",
        "phone": "13344445555",
        "status": "1",
    },
    {
        "id": "1",
        "username": "admin",
        "name": "管理员",
        "sex": "男",
        "phone": "13344445555",
        "status": "1",
    },
    {
        "id": "1",
        "username": "admin",
        "name": "管理员",
        "sex": "男",
        "phone": "13344445555",
        "status": "1",
    },
])
//分页条数据模型
const pageNum = ref(1)//当前页
const total = ref(20)//总条数
const pageSize = ref(10)//每页条数
//用户搜索时选中的产品id
const nameForSearch = ref('')

//使用标题共用编辑框
const title = ref('');
//控制抽屉是否显示
const visibleDrawer = ref(false)

//添加表单数据模型
const adminModel = ref({
    id: '',
    username: '',
    name: '',
    sex: '',
    phone: '',
    status: ''
})

//当每页条数发生了变化，调用此函数
const onSizeChange = (size) => {
    pageSize.value = size;
    getAdminWithCondition();
}
//当前页码发生变化，调用此函数
const onCurrentChange = (num) => {
    pageNum.value = num;
    getAdminWithCondition();
}


//获取Item商品详情
const getAdminWithCondition = async () => {
    //处理数据
    let params = {
        pageNum: pageNum.value,
        pageSize: pageSize.value,
        nameForSearch: nameForSearch.value ? nameForSearch.value : null,
    }
    let result = await adminListWithConditionService(params);
    if (result) {
        total.value = result.data.total;
        admins.value = result.data.list;
    }
}
getAdminWithCondition();


//清空数据回显
const clearData = () => {
    adminModel.value.id = '';
    adminModel.value.username = '';
    adminModel.value.name = '';
    adminModel.value.sex = '';
    adminModel.value.phone = '';
    adminModel.value.status = '';
}
//展示添加drawer
const showAddDrawer = () => {
    clearData();
    title.value = '添加员工';
    visibleDrawer.value = true;
}
//上传回显函数
const uploadSuccess = (result) => {
    adminModel.value.img = result.data;
    // console.log(articleModel);
    // console.log(result.data);
}
//展示编辑drawer
const showEditDrawer = (row) => {
    title.value = '编辑员工';
    visibleDrawer.value = true;
    //显示数据
    adminModel.value.id = row.id;
    adminModel.value.username = row.username;
    adminModel.value.name = row.name;
    adminModel.value.sex = row.sex;
    adminModel.value.phone = row.phone;
    adminModel.value.status = row.status;
    // //扩展id属性
    // articleModel.value.id = row.id;
}
//添加item
const add = async () => {
    console.log(adminModel.value);
    let result = await adminAddService(adminModel.value);
    ElMessage(result.message ? result.message : '添加成功');
    visibleDrawer.value = false;
    //保持条件查找
    getAdminWithCondition();
}
//编辑item
const edit = async () => {
    let result = await adminEditService(adminModel.value);
    ElMessage(result.message ? result.message : '编辑成功');
    visibleDrawer.value = false;
    //保持条件查找
    getAdminWithCondition();
}
//发布商品，可以是添加商品或者编辑商品
const publishAdmin = () => {
    title.value === '添加员工' ? add() : edit();
}

//删除商品
const deletefor = async (id) => {
    let result = await adminDeleteService(id);
    ElMessage(result.message ? result.message : '删除成功');
    getAdminWithCondition();
}
//删除商品弹窗
const deleteBox = (id) => {
    ElMessageBox.confirm(
        '您确定要删除这个员工吗',
        '注意',
        {
            confirmButtonText: '删除',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            deletefor(id);
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '删除取消',
            })
        })
}
//有条件搜索
const search = () => {
    getAdminWithCondition();
    ElMessage('获取成功');
}
//无条件搜索,用于重置
const searchWithNoCondition = () => {
    nameForSearch.value = null;
    getAdminWithCondition();
    ElMessage('获取成功');
}

// //删除商品
// const changeState = async (status,itemid) => {
//     let result = await itemChangeStateService(status,itemid);
//     ElMessage(result.message ? result.message : '删除成功');
//     getItemWithCondition();
// }
// //删除商品弹窗
// const changeStateBox = (status,itemid) => {
//     ElMessageBox.confirm(
//         '您确定要删除这个商品吗',
//         '注意',
//         {
//             confirmButtonText: '删除',
//             cancelButtonText: '取消',
//             type: 'warning',
//         }
//     )
//         .then(() => {
//             changeState(status,itemid);
//         })
//         .catch(() => {
//             ElMessage({
//                 type: 'info',
//                 message: '删除取消',
//             })
//         })
// }
const rules = {
    username: [
        { required: true, message: "不能为空", trigger: 'blur' },
        { pattern: /^.{1,10}$/, message: '用户名输入不超过10位', trigger: 'blur' }
    ],
    name: [
        { required: true, message: "不能为空", trigger: 'blur' },
        { pattern: /^.{1,10}$/, message: '名字不超过10个字', trigger: 'blur' }
    ],
    sex: [
        { required: true, message: "不能为空", trigger: 'blur' }  
    ],
    phone: [
        { required: true, message: "不能为空", trigger: 'blur' },
        { pattern: /^[1][3,4,5,6,7,8,9][0-9]{9}$/, message: '电话号码格式错误', trigger: 'blur' }  
    ],
    status: [
        { required: true, message: "不能为空", trigger: 'blur' }
    ]
}
</script>

<template>
    <el-card class="page-container">
        <template #header>
            <div class="header">
                <span>管理员成员管理</span>
                <div class="extra">
                    <el-button type="primary" @click="showAddDrawer()">添加员工</el-button>
                </div>
            </div>
        </template>
        <!-- 搜索表单 -->
        <el-form inline>
            <el-form-item label="员工姓名">
                <el-input v-model="nameForSearch" placeholder="请输入"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="search()">搜索</el-button>
                <el-button @click="searchWithNoCondition()">重置</el-button>
            </el-form-item>
        </el-form>
        <!-- Item列表 -->
        <el-table :data="admins" style="width: 100%">
            <el-table-column label="Id" prop="id"></el-table-column>
            <el-table-column label="用户名" prop="username"></el-table-column>
            <el-table-column label="姓名" prop="name"> </el-table-column>
            <el-table-column label="电话" prop="phone"></el-table-column>
            <el-table-column label="性别" prop="sex">
                <template #default="{ row }">
                    {{ sexHashmap.get(row.sex) || '未知状态' }}
                </template>
            </el-table-column>
            <el-table-column label="状态" prop="status">
                <template #default="{ row }">
                    {{ statusHashmap.get(row.status) || '未知状态' }}
                </template>
            </el-table-column>
            <el-table-column label="操作" width="160">
                <template #default="{ row }">
                    <el-button :icon="Edit" circle plain type="primary" @click="showEditDrawer(row)"></el-button>
                    <el-button :icon="Delete" circle plain type="danger" @click="deleteBox(row.id)"></el-button>
                    <!-- <el-button :icon="Edit" circle plain type="primary" @click="changeStateBox(row.status,row.itemid)">修</el-button> -->
                    <!-- todo 提供一个只修改状态的button -->
                </template>
            </el-table-column>
            <template #empty>
                <el-empty description="没有数据" />
            </template>
        </el-table>
        <!-- 分页条 -->
        <el-pagination v-model:current-page="pageNum" v-model:page-size="pageSize" :page-sizes="[3, 5, 10, 15]"
            layout="jumper, total, sizes, prev, pager, next" background :total="total" @size-change="onSizeChange"
            @current-change="onCurrentChange" style="margin-top: 20px; justify-content: flex-end" />
        <!-- 抽屉 -->
        <el-drawer v-model="visibleDrawer" :title="title" direction="rtl" size="50%">
            <!-- 添加/编辑商品表单 -->
            <el-form :model="adminModel" label-width="100px" :rules="rules">
                <el-form-item v-if="title==='编辑员工'" label="Id">
                    <el-input v-model="adminModel.id":disabled="true"></el-input>
                </el-form-item>
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="adminModel.username" placeholder="请输入"></el-input>
                </el-form-item>
                <el-form-item label="姓名" prop="name">
                    <el-input v-model="adminModel.name" placeholder="请输入"></el-input>
                </el-form-item>
                <el-form-item label="电话" prop="phone">
                    <el-input v-model="adminModel.phone" placeholder="请输入"></el-input>
                </el-form-item>
                <el-form-item label="性别" prop="sex">
                    <el-select placeholder="请选择" v-model="adminModel.sex">
                        <el-option v-for="c in sexOptions" :key="c.label" :label="c.label" :value="c.value">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="状态" prop="status">
                    <el-select placeholder="请选择" v-model="adminModel.status">
                        <el-option v-for="c in statusOptions" :key="c.label" :label="c.label" :value="c.value">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" width="500px" @click="publishAdmin()">完成</el-button>
                </el-form-item>
                <!-- 完成按钮增大宽度todo -->
            </el-form>
        </el-drawer>
    </el-card>
</template>
<style lang="scss" scoped>
.page-container {
    min-height: 100%;
    box-sizing: border-box;

    .header {
        display: flex;
        align-items: center;
        justify-content: space-between;
    }
}

/* 抽屉样式 */
.avatar-uploader {
    :deep() {
        .avatar {
            width: 178px;
            height: 178px;
            display: block;
        }

        .el-upload {
            border: 1px dashed var(--el-border-color);
            border-radius: 6px;
            cursor: pointer;
            position: relative;
            overflow: hidden;
            transition: var(--el-transition-duration-fast);
        }

        .el-upload:hover {
            border-color: var(--el-color-primary);
        }

        .el-icon.avatar-uploader-icon {
            font-size: 28px;
            color: #8c939d;
            width: 178px;
            height: 178px;
            text-align: center;
        }
    }
}

.editor {
    width: 100%;

    :deep(.ql-editor) {
        min-height: 200px;
    }
}
</style>